package com.usefullc.user.controller.client;


import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.enums.RegisterTypeEnum;
import com.usefullc.common.enums.SmsCodeTypeEnum;
import com.usefullc.common.enums.UserStatusEnum;
import com.usefullc.common.enums.UserTypeEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.entity.WebResult;
import com.usefullc.system.param.IdsParam;
import com.usefullc.system.service.component.ImgCodeComponent;
import com.usefullc.system.service.component.SmsComponent;
import com.usefullc.system.service.component.SystemConfigComponent;
import com.usefullc.system.validator.UsefulValid;
import com.usefullc.user.domain.User;
import com.usefullc.user.param.*;
import com.usefullc.user.query.UserQuery;
import com.usefullc.user.service.EmployeeService;
import com.usefullc.user.service.UserService;
import com.usefullc.user.service.component.UserManager;
import com.usefullc.user.vo.LoginResultVo;
import com.usefullc.user.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-03-19 12:02
 */
@RestController
@RequestMapping(path = "/user/c/")
@Api(tags = "C端用户管理")
public class ClientUserController {

    @Autowired
    private ImgCodeComponent imgCodeComponent;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private UserService userService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private SystemConfigComponent systemConfigComponent;

    @ApiOperation(value = "获取图形验证码",  response = WebResult.class)
    @GetMapping(path = "getImgCode", produces = "application/json")
    public WebResult getImgCode(CheckCodeParam param) {
        String deviceId = param.getDeviceId();
        Integer checkCodeType = param.getCheckCodeType();
        String imgCode = imgCodeComponent.getImgCode(checkCodeType, UserTypeEnum.MEMBER.getCode(), deviceId);
        return WebResultBuilder.successResult(imgCode);
    }

    @ApiOperation(value = "获取短信验证码",  response = WebResult.class)
    @GetMapping(path = "getSmsCode", produces = "application/json")
    public WebResult getSmsCode(UserLoginParam param) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        smsComponent.getImgCode(param.getCheckCodeType(), UserTypeEnum.MEMBER.getCode(),"86",param.getMobile());
        return WebResultBuilder.successResult();
    }


//    @ApiOperation(value = "获取忘记密码短信验证码",  response = WebResult.class)
//    @GetMapping(path = "getForgetPwdSmsCode", produces = "application/json")
//    public WebResult getForgetPwdSmsCode(UserLoginParam param) {
////        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
//        smsComponent.getImgCode(SmsCodeTypeEnum.FORGET_PASSWORD.getCode(),UserTypeEnum.ADMIN.getCode(),"86",param.getMobile());
//        return WebResultBuilder.successResult();
//    }




    @ApiOperation(value = "获取当前登录用户信息",  response = WebResult.class)
    @GetMapping(path = "getLoginUserInfo", produces = "application/json")
    public WebResult getLoginUserInfo(HttpServletRequest request) {
        UserVo user = userService.getLoginUser(request);
        if(user == null){
            return WebResultBuilder.failedResult("没有用户信息");
        }
        return WebResultBuilder.successResult(user);
    }

    @ApiOperation(value = "用户分页列表", response = WebResult.class)
    @GetMapping(path = "list", produces = "application/json")
    public WebResult list(UserQuery query) {
//        query.setType(UserTypeEnum.ADMIN.getCode());
        Pager<UserVo> page = userService.findVoByPage(query);
        return WebResultBuilder.successResult(page);
    }

    @ApiOperation(value = "用户所有列表", response = WebResult.class)
    @GetMapping(path = "listAll", produces = "application/json")
    public WebResult listAll(UserQuery query) {
//        query.setType(UserTypeEnum.ADMIN.getCode());
        List<User> dataList = userService.findAll(query);
        return WebResultBuilder.successResult(dataList);
    }


    @ApiOperation(value = "用户详情", response = WebResult.class)
    @GetMapping(path = "detail", produces = "application/json")
    public WebResult detail(@ApiParam(value = "用户ID", required = true, example = "1") @Valid @RequestParam Long id) {
        User user = userService.findById(id);
        return WebResultBuilder.successResult(user);
    }


    @ApiOperation(value = "根据短信验证码修改忘记密码", response = WebResult.class)
    @PostMapping(path = "updateForgetLoginPwdBySmsCode", produces = "application/json")
    public WebResult updateForgetLoginPwdBySmsCode(@RequestBody UserLoginParam param, HttpServletRequest request) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        userService.updateForgetLoginPwdBySmsCode(UserTypeEnum.MEMBER.getCode(), "86",param.getMobile(),  param.getCheckCode(),param.getPwd());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "检查账户或手机号是否唯一",  response = WebResult.class)
    @PostMapping(path = "checkUserUnique", produces = "application/json")
    public WebResult checkUserUnique(@RequestBody UserRegisterParam param) {
        if(StringUtils.isNotEmpty(param.getAccountNo())){
            boolean unique = this.userService.checkUserUniqueByAccountNo(UserTypeEnum.MEMBER.getCode(), param.getAccountNo());
            if(!unique){
                throw new BizException("账号已存在");
            }
        }else if(StringUtils.isNotEmpty(param.getMobile())){
            boolean unique = this.userService.checkUserUniqueByMobile(UserTypeEnum.MEMBER.getCode(), param.getMobile());
            if(!unique){
                throw new BizException("手机号码已存在");
            }
        }
        return WebResultBuilder.successResult();
    }



    @ApiOperation(value = "用户登录[密码]", response = WebResult.class)
    @PostMapping(path = "login", produces = "application/json")
    public WebResult login(@UsefulValid @RequestBody UserLoginParam param, HttpServletRequest request) {
        String deviceId = param.getDeviceId();
        User user = userService.loginByPwd(UserTypeEnum.MEMBER.getCode(), param.getAccountNo(), param.getPwd(), param.getCheckCode(), deviceId);
        String token = userService.resetLoginToken(user);
        LoginResultVo loginResultVo = new LoginResultVo();
        loginResultVo.setToken(token);
        UserVo userVo = BeanUtils.beanCopy(user, UserVo.class);
        loginResultVo.setUserInfo(userVo);
        return WebResultBuilder.successResult(loginResultVo);
    }


    @ApiOperation(value = "用户登录[验证码]", response = WebResult.class)
    @PostMapping(path = "loginByMobile", produces = "application/json")
    public WebResult loginByMobile(@UsefulValid @RequestBody UserLoginParam param, HttpServletRequest request) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
//        User user = userService.loginByPwd(UserTypeEnum.ADMIN.getCode(), param.getAccountNo(), param.getPwd(), param.getImgCode(), deviceId);
        User user = userService.loginBySmsCode(UserTypeEnum.MEMBER.getCode(), "86", param.getMobile(), param.getCheckCode());
        String token = userService.resetLoginToken(user);
        LoginResultVo loginResultVo = new LoginResultVo();
        loginResultVo.setToken(token);
        UserVo userVo = BeanUtils.beanCopy(user, UserVo.class);
        loginResultVo.setUserInfo(userVo);
        return WebResultBuilder.successResult(loginResultVo);
    }


    @ApiOperation(value = "用户注册", response = WebResult.class)
    @PostMapping(path = "register", produces = "application/json")
    public WebResult register(@UsefulValid @RequestBody UserRegisterParam param) {
        param.setUserType(UserTypeEnum.MEMBER.getCode());
        if(param.getRegisterType() == RegisterTypeEnum.MOBILE.getCode()){
            throw new BizException("暂不支持其他类型注册",false);
//            if(StringUtils.isEmpty(param.getAreaCode())){
//                param.setAreaCode("86");
//            }
//            userService.register(param);
        }else if(param.getRegisterType() == RegisterTypeEnum.ACCOUNT.getCode()){
            if (StringUtils.isEmpty(param.getAccountNo())) {
                throw new BizException("账号不能为空",false);
            }
            if (StringUtils.isEmpty(param.getPwd())) {
                throw new BizException("密码不能为空",false);
            }
            User user = userService.registerByAccount(param);
            //注册后，需要手动手动获取用户信息，因为有些注册需要审核
//            String token = userService.resetLoginToken(user);
//            LoginResultVo loginResultVo = new LoginResultVo();
//            loginResultVo.setToken(token);
//            UserVo userVo = BeanUtils.beanCopy(user, UserVo.class);
//            loginResultVo.setUserInfo(userVo);
            return WebResultBuilder.successResult(user);
        }else{
            throw new BizException("暂不支持其他类型注册",false);
        }
    }


    @ApiOperation(value = "用户注销",  response = WebResult.class)
    @PostMapping(path = "logout", produces = "application/json")
    public WebResult logout(HttpServletRequest request) {
        userService.clearLoginUser(request);
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "保存用户", response = WebResult.class)
    @PostMapping(path = "save", produces = "application/json")
    public WebResult save(@UsefulValid(save=true) @RequestBody UserEditParam param) {
        User user = BeanUtils.beanCopy(param, User.class);
        this.userService.saveUser(user,param);
        return WebResultBuilder.successResult(user);
    }


    @ApiOperation(value = "修改用户", response = WebResult.class)
    @PostMapping(path = "update", produces = "application/json")
    public WebResult update(@UsefulValid(update = true) @RequestBody UserEditParam param) {
        User user = this.userService.findById(param.getId());
        BeanUtils.beanCopy(param,user);
        this.userService.saveUser(user,param);
        return save(param);
    }


    @ApiOperation(value = "绑定员工", response = WebResult.class)
    @PostMapping(path = "bingEmployee", produces = "application/json")
    public WebResult bingEmployee(@UsefulValid @RequestBody BindEmployeeParam param) {
        EmployeeEditParam employeeEditParam = BeanUtils.beanCopy(param, EmployeeEditParam.class);
        employeeService.saveEmployee(employeeEditParam);
        return WebResultBuilder.successResult();
    }


    @ApiOperation(value = "删除用户", response = WebResult.class)
    @PostMapping(path = "del", produces = "application/json")
    public WebResult del(@UsefulValid @RequestBody IdsParam idsParam) {
        userService.deletePhysByIds(idsParam.getIds());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "自己修改密码", response = WebResult.class)
    @PostMapping(path = "updatePwd", produces = "application/json")
    public WebResult updatePwd(@UsefulValid @RequestBody UpdatePwdParam param) {
        UserVo loginUser = UserManager.getLoginUser();
        userService.updatePwd(loginUser.getId(), param.getOldPwd(), param.getNewPwd());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "管理员重置密码", response = WebResult.class)
    @PostMapping(path = "resetPwd", produces = "application/json")
    public WebResult resetPwd(@UsefulValid @RequestBody IdsParam param) {
        String pwd = userService.resetPwd(param.getIds());
        return WebResultBuilder.successResult(pwd);
    }


    @ApiOperation(value = "冻结", response = WebResult.class)
    @PostMapping(path = "freeze", produces = "application/json")
    public WebResult freeze(@UsefulValid @RequestBody IdsParam idsParam) {
//        userService.updateAllStatus(idsParam.getIds(), UserStatusEnum.NOT_PASS.getCode());
        userService.getBaseMapper().updateAllStatus(idsParam.getIds(), UserStatusEnum.NOT_PASS.getCode());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "解冻", response = WebResult.class)
    @PostMapping(path = "unFreeze", produces = "application/json")
    public WebResult unFreeze(@UsefulValid @RequestBody IdsParam idsParam) {
        userService.updateAllStatus(idsParam.getIds(), UserStatusEnum.PASS.getCode());
        return WebResultBuilder.successResult();
    }



}
